#!/usr/bin/env bash

# need additional step to not redefine variables value if already set
\typeset old_rvm_verbose_flag old_rvm_debug_flag >/dev/null 2>/dev/null
old_rvm_verbose_flag=${rvm_verbose_flag:-0}
old_rvm_debug_flag=${rvm_debug_flag:-0}

# silence Zsh redefinitions
\typeset rvm_verbose_flag rvm_debug_flag hooks >/dev/null 2>/dev/null

true rvm_verbose_flag:${rvm_verbose_flag:=${old_rvm_verbose_flag}} \
  rvm_hooks_path:${rvm_hooks_path:="$rvm_path/hooks"} \
  rvm_debug_flag:${rvm_debug_flag:=${old_rvm_debug_flag}} rvm_hook:${rvm_hook:=}

if
  [[ -n "$rvm_hook" ]]
then
  hooks=()
  if
    [[ -d "$rvm_hooks_path" ]]
  then
    hooks+=( "$rvm_hooks_path" )
  fi
  if
    [[ "$PWD/.rvm/hooks" != "$rvm_hooks_path" && -d "$PWD/.rvm/hooks" ]]
  then
    hooks+=( "$PWD/.rvm/hooks" )
  fi

  if
    [[ -n "${hooks[*]}" ]]
  then
    __rvm_read_lines _hooks_list <(
      __rvm_find -L "${hooks[@]}" -iname "$rvm_hook*" -type f 2>/dev/null || true
    )
    for hook in "${_hooks_list[@]}"
    do
      if
        [[ -x "${hook}" || "${hook##*/}" == "$rvm_hook" ]]
      then
        if
          [[ "${hook}" == "$rvm_hooks_path/"* ]] ||   # trust internal hooks
          __rvm_check_rvmrc_trustworthiness "${hook}" # ask user to trust other files
        then
          rvm_debug "Running $hook"
          __rvm_conditionally_do_with_env . "${hook}" >&2
        fi
      fi
    done
  fi
fi

unset rvm_hook hooks _hooks_list hook
